package dn.easy.common.baserx;

import android.content.Context;

import dn.easy.common.commonwidget.AVLoadingDialog;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandlerFactory;

/**
 * ================================================
 * Created by JessYan on 9/2/2016 14:41
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public abstract class ErrorHandleSubscbscriber<T> implements Observer<T> {
    private ErrorHandlerFactory mHandlerFactory;
    private boolean mIsShowLoading = false;
    private Context mContext;

    public ErrorHandleSubscbscriber(RxErrorHandler rxErrorHandler, boolean isShowLoading, Context context) {
        this.mHandlerFactory = rxErrorHandler.getHandlerFactory();
        this.mIsShowLoading = isShowLoading;
        this.mContext = context;
    }


    @Override
    public void onSubscribe(@NonNull Disposable d) {
        if (mIsShowLoading) {
            AVLoadingDialog.showDialogForLoading(mContext);
        }
    }


    @Override
    public void onComplete() {
        AVLoadingDialog.cancelDialogForLoading();
    }


    @Override
    public void onError(@NonNull Throwable t) {
        t.printStackTrace();
        AVLoadingDialog.cancelDialogForLoading();
        //如果你某个地方不想使用全局错误处理,则重写 onError(Throwable) 并将 super.onError(e); 删掉
        //如果你不仅想使用全局错误处理,还想加入自己的逻辑,则重写 onError(Throwable) 并在 super.onError(e); 后面加入自己的逻辑
        mHandlerFactory.handleError(t);
    }
}

